package com.tycoin.app.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.tycoin.AppGlobal;

@Aspect
@Component
public class ApiControllerAspect {
	private final Logger logger = LoggerFactory.getLogger(ApiControllerAspect.class);

	@Before("execution(public * com.tycoin..*.*Controller.*(..))")
	public void beforeInit(JoinPoint pjp) throws Throwable {
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		// HttpServletResponse response = ((ServletRequestAttributes)
		// RequestContextHolder
		// .getRequestAttributes()).getResponse();
		// Cookie[] cookies = request.getCookies();
		// if (null != cookies) {
		// for (Cookie cookie : cookies) {
		// logger.info("cookie.getName()=" + cookie.getName() + ",value="
		// + cookie.getValue());
		// }
		// }
		
		String requestServletPath = StringUtils.trimToEmpty(request.getServletPath());
		String QueryString = request.getQueryString();
 
		StringBuffer current_page_url = new StringBuffer();
		current_page_url.append(requestServletPath);
		if (StringUtils.isNotEmpty(QueryString)) {
			current_page_url.append("?");
			current_page_url.append(QueryString);
		}
		request.setAttribute("current_page_url", AppGlobal.webAccessUrl + current_page_url.toString());
		logger.info("beforeInit:" + current_page_url.toString());
	}

	@After("execution(public * com.tycoin..*.*Controller.*(..))")
	public void afterInit() throws Throwable {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();
		if (response.getStatus() == 200) {
			String requestServletPath = StringUtils.trimToEmpty(request.getServletPath());
			request.setAttribute("requestServletPath", requestServletPath);
		}
	}
}
